/**
 * Created by liutong on 17/5/11.
 *
 * 需要：接收file元素(第一个参数) 和imgDOM元素(第二个参数)
 * 返回 :  直接在第二个img元素上设置src属性
 *
 * */

import React from 'react';

function UpLoacalFile(file,callback) {

    var isIE = navigator.userAgent.match(/MSIE/)!= null,
        isIE6 = navigator.userAgent.match(/MSIE 6.0/)!= null;

    if(isIE) {
        file.select();
        var reallocalpath = document.selection.createRange().text;

        // IE6浏览器设置img的src为本地路径可以直接显示图片
        if (isIE6) {
            pic.src = reallocalpath;
        }else {
            // 非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片，但是可以通过滤镜来实现
            pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
            // 设置img的src为base64编码的透明图片 取消显示浏览器默认图片
            pic.src = '';
        }
    }else {
        getBase64(file,callback)
    }
}

const getBase64 = (img,callback)=>{
    const reader = new FileReader();
    reader.addEventListener("load",function(){
        callback(this.result)
    });
    reader.readAsDataURL(img);
};

// 伪UI 组件
function SelfView (props){

    const {C} = props;

    return(
        <div className="fly-localUpload-avatar">
            <span className="fly-localUpload" onClick={(e)=>C(e)} role="button" tabIndex="0">
                {
                    props.children
                }
            </span>
        </div>
    )
}


// http上传文件
class UpLoadCloudBatch extends React.Component{

    constructor(props){
        super(props);
        this.state={

        }
        this.callBack = this.callBack.bind(this);
    }

    componentWillMount(){

    }

    componentDidUpdate(){
        if(this.props.isUpdata){
            const L = this.props.fileList;

            // --- 必选参数 : action --- //
            if(L.length >= 0 ){
                if(!this.props.action){ return; }
                const p = this.props,
                      data = p.data;

                let d = {},upOption = {action : p.action}

                if(data){
                    // 两种方式 function ｜ object
                    if(typeof data === "function"){
                        const o = data(file);
                        Object.prototype.toString.call(o) === "[object Object]" && dataUpload(data());
                    }else{
                        Object.prototype.toString.call(data) === "[object Object]" && dataUpload(data);
                    }
                    upOption.data = d;   // 添加data
                }


                //--- 添加其他的参数 ::_data type.Object ---//
                function dataUpload(_data) {
                    // 添加props中的参数
                    if(data && Object.prototype.toString.call(_data) === "[object Object]"){
                        d = JSON.parse(JSON.stringify(_data));
                    }
                }

                // 伦循上传
                for(let k in L){
                    // ::纯file文件 ::callback  ::key值
                    this.HttpUploadFile(L[k],this.callBack,k,upOption)
                }
            }
        }
    }


    componentDidMount(){

    }

    callBack(file,res,k,{status,des}){

        const o = this.deepCopy(file);

        // 添加需要的属性
        o.originFileObj= null;
        o.response = null;
        o.progress = null;
        o.uid = null;
        o.error = null;
        o.status = status;

        if(status === "success"){
            o.response = JSON.parse(res);

            // 完成
            o.originFileObj = file;

        }else if( status === "error" ){
            o.error = des;
        }else if( status === "uploading" ){
            o.progress = des
        }

        if(status !== "error"){
            o.uid = this.uuid();
            o.originFileObj = file;
        }

        // 派出
        this.props.onChange(o,k);
    }

    HttpUploadFile(file,callback,key,{action,data}){

        if(!file || !key) { return; }

        let upLoadUrl = action,
            xhr = new XMLHttpRequest();

        const i = key;

        let formData = new FormData();

        xhr.open("POST", upLoadUrl, true);

        formData.append('file', file);

        for(let key in data){formData.append(key,data[key]);}


        xhr.onreadystatechange = () => {
            if (xhr.readyState != 4) { return }

            if (xhr.status == 200) {
                callback && callback(file,xhr.response,i,{status:"done",des:""})
            }
        };

        xhr.upload.onprogress = (e)=>{
            const gress = parseInt(100*e.loaded/e.total,10);
            callback && callback(file,null,null,{status:"uploading",des:e});
        };

        xhr.onload = ()=>{
            console.log("上传完成");
        };

        xhr.onerror = (e)=>{
            console.log(`出现错误${e}`);
            callback && callback(file,xhr.response,i,{status:"error",des:e});
        };

        xhr.send(formData);
    }


    uuid(b){
        return `xxxxxxxx-${b}-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,(c)=>{
            let r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    }

    deepCopy (obj){
        let t = null;

        const type = Object.prototype.toString.call(obj) === "[object Array]"
            ? t = [] : t = {};

        if(t){
            for(let key in obj){
                // obj :: obj类型 单独属性
                if(Object.prototype.toString.call(obj[key]) === "[object Object]") {
                    // 判断没有属性值或不可枚举的对象
                    if( Object.getOwnPropertyNames(obj).length <= 0 ){
                        t = obj;
                        return t;
                    }else{
                        return this.deepCopy(obj[key]);
                    }
                }else{
                    t[key] = obj[key];
                }
            }
        }
        // t:: object || array
        return t;
    };

    render(){
        return(
            <div>

            </div>
        )
    }
}


// 做好本地传输  只负责输出本地的files
class UpLocalLoad extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            fileList:[],
            T:true   //负责切换input 的state
        };


        // 方法绑定
        this.trigger = this.trigger.bind(this);
        this.handleFileChange = this.handleFileChange .bind(this);
    }

    /**
     *   __proto__
     * */
    componentWillMount(){
        // 抽取外部props，非空判断
        const p = this.props;
        // 伪空 null + undefined
        p["accept"] == null  ? this.InputProps["accept"] = "" :
            this.InputProps["accept"] = this.props.accept;

        // if(p["multiple"] == null) {this.InputProps["multiple"] = "";}
    }


    /**
     *   self
     * */

    // 伪触发input上传事件
    trigger(event){
        if(this.props.isSelect === false) { return; }

        this.refs.input.click()
    }

    InputProps = {};


    guid(b){
        return `xxxxxxxx-${b}-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,(c)=>{
            let r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    }

    // change 上传文件
    handleFileChange(e){

        // 刚才上传的文件
        const files = e.target.files,
            B = this.props.beforeUpload;

        let c = this.props.onChange,
            o = {},
            curList = [];

        // 无论是否为单个或多个 都先转换为纯数组并深拷贝一份.
        // curList = JSON.parse(JSON.stringify([...Array.from(files)]));
        let ArFiles = [...Array.from(files)];

        curList = ArFiles.map((item,index)=>{
           //  ::item object
            let o = {};
            for(let key in item){
                // 自有属性
                if(typeof item[key] === "function") continue;

                if(typeof item[key] === "object"){
                    o[key] = deepCopy(item[key]);
                }else{
                    o[key] = item[key];
                }
            }

            o.error = null;

            o.uid = this.guid("upload");

            o.originFileObj = item;

            o.status = null;

            return o;
        });

        function deepCopy (obj){

            let t = null;

            const type = [].toString.call(obj) === "[object Array]"
                ? t = [] : t = {};

           // obj :: obj类型 单独属性
           if([].toString.call(t) === "[object Object]") {
               // 判断没有属性值或不可枚举的对象
               if( Object.getOwnPropertyNames(obj).length <= 0 ){
                   t = obj;
                   return t;
               }
           }

            if(t){
                for(let key in obj){
                    t[key] = obj[key];
                }
            }
            // t:: object || array
            return t;
        };


        // 如果是多选就是list，否则就是一个
        const curFile = files.length>1 ? curList : curList[0]

        //运行before函数;
        if(B.call(null,curList) === false){return}

        //统一给file添加一个状态标示[本地上传状态]
        curList.map((item,index)=>{item.status = "local"});

        // 把当前上传的文件push到内部状态
        this.setState({fileList:curList});

        o.file = curFile;       // object类型 | 数组[多选]
        o.fileList = curList;   // 数组格式
        o.event = e;            // event

        // 暴露外部接口
        c(o);

        // 更新input;
        this.setState({T:!this.state.T})
    }


    render() {
        const {accept} = this.props,
            {T} = this.state;
        return(
            <div className="fly-localUpload">
                {/*触发元素留给用户自己*/}
                <div
                    ref="trigger"
                    className="fly-localUpload-trigger"
                >
                    {/*展示区域 在本区域展示*/}


                    <SelfView
                        C={this.trigger}
                    >

                        {
                            T? <input key="true" type="file"
                                      ref="input"
                                      style={{display:"none"}}
                                      accept={this.InputProps.accept}
                                      onChange={this.handleFileChange}

                            /> : <input  key="false" type="file"
                                         ref="input"
                                         style={{display:"none"}}
                                         accept={this.InputProps.accept}
                                         onChange={this.handleFileChange}
                            />
                        }


                        {
                            this.props.children
                        }
                    </SelfView>


                    {/*列表式 UI组件*/}
                    {/*文本式UI组件*/}
                </div>
            </div>
        )
    }
}

export {UpLocalLoad,UpLoadCloudBatch,UpLoacalFile}
